package com.iwhalecloud.bss.kite.cucc.service.attr.linkhandler;

import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.service.attr.handler.LimitRateAttrHandler;
import com.iwhalecloud.bss.kite.listener.handler.attr.annotation.AttrHandler;
import com.iwhalecloud.bss.kite.listener.handler.attr.impl.AbstractAttrLinkageHandler;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.service.attr.AttrData;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * @author ljy
 * @version 1.0.0
 * @ClassName LimitRateLinkAttrHandler.java
 * @createTime 2021年11月04日 14:41:00
 */
@Service
@AttrHandler(LimitRateAttrHandler.class)
public class LimitRateLinkAttrHandler extends AbstractAttrLinkageHandler<AttrData> {

    @Override
    public void handle(KiteAttr attr, KiteInst inst, AttrData data) {
        // 跨境、穿境、纯境外 限速小于等于带宽
        String goodId = inst.getSpecId();
        if (KiteStringUtils.equalsAny(goodId, "60040446", "60040447", "60040444")) {
            String dkValue = inst.getAttr("2_0000001").getValueDesc();
            String xsValue = inst.getAttr("2_0000005").getValueDesc();
            if (KiteStringUtils.isEmpty(dkValue) || KiteStringUtils.isEmpty(xsValue)){
                return;
            }
            BigDecimal dk = unitConversion(dkValue);
            BigDecimal xs = unitConversion(xsValue);
            if (xs.compareTo(dk)==1){
                ErrorConsts.BUSI_COMMON_ERROR.throwOut("限速不能大于带宽，请重新选择！" );
            }
        }
    }

    /**
     * 带宽、限速单位统一转换为M
     */
    public BigDecimal unitConversion(String str) {
        BigDecimal bigval = new BigDecimal(str.replaceAll("[^0-9]", ""));
        List<String> list = Arrays.asList("K", "G");
        if (str.contains(list.get(0))) {
            BigDecimal bigDecimal = BigDecimal.valueOf(Math.pow(2.0, -10));
            bigval = bigval.multiply(bigDecimal);
        }
        if (str.contains(list.get(1))) {
            BigDecimal bigDecimal = BigDecimal.valueOf(Math.pow(2.0, 10));
            bigval = bigval.multiply(bigDecimal);
        }
        return bigval;
    }

    @Override
    public void handleStyle(KiteAttr attr, KiteInst inst, AttrData data) {

    }
}
